﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemCenterSoa.BaseLibrary.Tools.TypeTools;
using SystemCenterSoa.DtoModel.Common;
using SystemCenterSoa.DtoModel.SystemManager;
using SystemCenterSoa.IRepository.SystemManager;
using SystemCenterSoa.PoModel.SystemManager;
using SystemCenterSoa.Repository.CommonLib;

namespace SystemCenterSoa.Repository.SystemManager
{
    //RoleRepository
    public class RoleRepository : BaseRepository, IRoleRepository
    {

        //注入ef的的上下文
        public RoleRepository(SystemCenterDbSoaContext SystemCenterDbSoaContext) : base(SystemCenterDbSoaContext)
        {

        }
        //显示一条数据
        public RoleDto GetRoleDtoById(int roleId)
        {
            var RolePo = _systemCenterDbSoaContext.RolePo.FirstOrDefault(c => c.role_id == roleId);
            if (RolePo == null) return null;
            RoleDto view = ModelCopier.CreateInstanceFrom<RoleDto>(RolePo);
            view.roleModuleCode = _systemCenterDbSoaContext.RoleModuleRelationPo.
                Where(c => c.role_id == roleId).Select(b => b.module_code).ToList();
            return view;
        }

        public PagerResult<RolePo> SearchPage(SearchModel searchModel)
        {
            //设置隐射，表的隐射
            var query = _systemCenterDbSoaContext.RolePo.AsQueryable();
            //首先判断方法给的数据是否有值，在进行判断有几个，如果没有值或者个数为0则不进行继续执行，如果两个条件都符合则继续执行
            if (searchModel.SearchItem != null && searchModel.SearchItem.Count > 0)
            {
                var tempDi = searchModel.SearchItem;
                //搜索字段为role_name
                string roleName = "role_name";
                //判断搜索条件中是否有role_name
                if (tempDi.Keys.Contains(roleName) && !string.IsNullOrEmpty(tempDi[roleName]))
                {
                    query = query.Where(c => c.role_name.Contains(tempDi[roleName]));
                }

                string roleStatus = "role_status";
                //判断搜索条件中是否有role_name
                if (tempDi.Keys.Contains(roleStatus) && !string.IsNullOrEmpty(tempDi[roleStatus]))
                {
                    int tempStatus = -1;
                    if (int.TryParse(tempDi[roleStatus], out tempStatus))
                    {
                        query = query.Where(c => c.role_status == tempStatus);
                    }

                }
                if (!string.IsNullOrEmpty(searchModel.OrderBy))
                {
                    if (searchModel.OrderBy == "role_id")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.role_id);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.role_id);
                        }
                    }


                    if (searchModel.OrderBy == "role_name")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.role_name);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.role_name);
                        }
                    }
                }
            }
            //封装的方法，显示总行数巴拉巴拉的那些
            return BasePageSearch(query, searchModel);
            //提取总行数
            //int total = query.Count();
            //PagerResult<RolePo> result = new PagerResult<RolePo>()
            //{
            //    PageCount = (int)Math.Ceiling((decimal)total / searchModel.PageSize),
            //    Total = total,

            //    Data = query.Skip(searchModel.Start).Take(searchModel.End).ToList(),
            //    PageIndex = searchModel.PageIndex
            //};
            //return result;
        }




        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public int RolePoAdd(RoleDto view)
        {
            //命名空间，用于事务回滚，如果中途出现意外，就立即回滚数据
            using (var tran = _systemCenterDbSoaContext.Database.BeginTransaction())
            {
                try
                {
                    RolePo db = ModelCopier.CreateInstanceFrom<RolePo>(view);
                    _systemCenterDbSoaContext.RolePo.Add(db);//添加进去
                    _systemCenterDbSoaContext.SaveChanges();//然后提交，保存一下
                    List<RoleModuleRelationPo> rmrs = new List<RoleModuleRelationPo>();
                    if (view.roleModuleCode != null && view.roleModuleCode.Count > 0)
                    {
                        foreach (var mc in view.roleModuleCode)
                        {
                            rmrs.Add(new RoleModuleRelationPo()
                            {
                                role_id = db.role_id,
                                module_code = mc,
                                creator_date = db.creator_date,
                                creator_name = db.creator_name
                            }
                                );
                        }
                        _systemCenterDbSoaContext.RoleModuleRelationPo.AddRange(rmrs);
                        _systemCenterDbSoaContext.SaveChanges();//赋值之后在一次提交
                    }
                    tran.Commit();//提交事务
                    return db.role_id;
                }
                catch (Exception ex)
                {
                    tran.Rollback();//事务回滚，出现错误进行回滚
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 两表修改，用到事务，可以及时回滚。先删角色模块表，在插入新的角色模块记录
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public bool RoleUpdate(RoleDto view)
        {
            //事务的作用是可以在发生异常的时候及时回滚，不用造成损失
            using (var tran = _systemCenterDbSoaContext.Database.BeginTransaction())
            {
                try
                {
                    var RolePo = _systemCenterDbSoaContext.RolePo.FirstOrDefault(p => p.role_id == view.role_id);

                    ModelCopier.CopyModel(view, RolePo, "creator_name", "creator_date");
                    _systemCenterDbSoaContext.SaveChanges();

                    string delSql = "delete role_module_relation where role_id=({0})";
                    _systemCenterDbSoaContext.Database.ExecuteSqlRaw(delSql, RolePo.role_id);
                    List<RoleModuleRelationPo> rmrs = new List<RoleModuleRelationPo>();
                    if (view.roleModuleCode != null && view.roleModuleCode.Count > 0)
                    {
                        foreach (var mc in view.roleModuleCode)
                        {
                            rmrs.Add(new RoleModuleRelationPo()
                            {
                                role_id = RolePo.role_id,
                                module_code = mc,
                                creator_date = RolePo.modifi_date.Value,
                                creator_name = RolePo.modifi_name
                            });
                        }
                        _systemCenterDbSoaContext.RoleModuleRelationPo.AddRange(rmrs);
                        _systemCenterDbSoaContext.SaveChanges();
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        //获取对应用户下面的角色获取，用中间表，进行联查获取
        //查询指定用户名下面的角色
        public List<RolePo> GetRolePosByUserName(string userName)
        {
            //根据姓名进行查询
            return (from r in _systemCenterDbSoaContext.RolePo
                    join arr in _systemCenterDbSoaContext.AdminUserRoleRelationPo on r.role_id equals arr.role_id
                    where arr.user_name == userName
                    select r).ToList();
        }
    }
}
